<!--
 * @Descripttion: unTitle
 * @Author: yizheng.yuan
 * @Date: 2021-11-16 10:20:44
 * @LastEditors: yizheng.yuan
 * @LastEditTime: 2021-11-16 13:52:16
-->
<template>
  <div class="vCenter">
    <div class="about">
      <h1>登录页面</h1>
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="ruleForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="ruleForm.password"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">登录</el-button>
          <el-button>取消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        ruleForm: {
          username: '',
          password: ''
        },
        rules: {
          username: [
            { required: true, message: '不能为空', trigger: 'blur' },
          ],
          password: [
            { required: true, message: '不能为空', trigger: 'blur' }
          ],
        }
      }
    },
    methods: {
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            // alert('submit!');
            // 提交给后台
            this.$axios({
                method:'post',
                url:'/api/login',
                data: this.ruleForm
            }).then((response) =>{          //这里使用了ES6的语法
                console.log('成功',response)       //请求成功返回的数据
                if(response.data.error>0){
                  this.$message({
                    message: response.data.msg,
                    type: 'warning'
                  });
                }else{
                  this.$message({
                    message: '登录成功！',
                    type: 'success'
                  });

                  // 这里登录成功了
                  // 保存username到localStorage
                  window.localStorage.setItem('username',this.ruleForm.username);
                  // 将用户名保存到vuex
                  this.$store.commit('updateUsername', this.ruleForm.username)
                  // 跳转到首页
                  this.$router.push('/')
                }
            }).catch((error) =>{
                console.log('登录出错',error)       //请求失败返回的数据
            })
            
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      }
    }
  }
</script>

<style scoped>
/* 垂直居中 */
.vCenter{
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}
.about{
  width: 350px;
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 6px;
  box-shadow: 0 0 25px #ccc;
}
</style>
